package com.unionftech.crm_android.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.unionftech.baselibrary.glide.GlideImagerLoader
import com.unionftech.common.CommonConstants
import com.unionftech.common.R.string
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.BannerImageInfo
import com.unionftech.common.common.bean.BannerPosition
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.router.service.ILoginService
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.StatusBarUtil
import com.unionftech.common.utils.Utils
import com.unionftech.crm_android.R
import com.unionftech.crm_android.adapter.IntroductionInfo
import com.unionftech.crm_android.adapter.IntroductionPagerAdapter
import kotlin.math.abs


class UFIntroductionActivity : BaseMvpActivity(), CommonContract.IBannerView {
    private val mViewPager: ViewPager2 by lazy { mRootView.findViewById(R.id.view_pager) }
    private val mTvJump: TextView by lazy { mRootView.findViewById(R.id.tv_jump) }
    private val mLlIndicator: LinearLayout by lazy { mRootView.findViewById(R.id.ll_indicator) }
    private lateinit var mAdapter: IntroductionPagerAdapter
    private val mIntroductionList by lazy { mutableListOf<IntroductionInfo>() }
    private val mIndicatorViews by lazy { mutableListOf<ImageView>() }
    private var mLastX = 0f
    private val swipeThreshold = 150 // 滑动阈值(px)

    @Autowired
    @JvmField
    var mLoginService: ILoginService? = null

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter

    init {
        ARouter.getInstance().inject(this)
    }

    companion object {
        private const val TAG = "UFIntroductionActivity"

        @JvmStatic
        fun startThis(context: Context) {
            val intent = Intent(context, UFIntroductionActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }


    override fun initLayout() = R.layout.activity_uf_introduction

    override fun initData() {
        super.initData()
        initIntroductionData()
        mAdapter = IntroductionPagerAdapter(mIntroductionList)
    }

    private fun initIntroductionData() {
        mIntroductionList.add(
            IntroductionInfo(R.drawable.icon_introduction_1, null)
        )
        mIntroductionList.add(
            IntroductionInfo(R.drawable.icon_introduction_2, null)
        )
        mIntroductionList.add(
            IntroductionInfo(R.drawable.icon_introduction_3, null)
        )
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvJump.text = DynamicResourceManager.getString(mContext, string.skip)
    }

    override fun setListener() {
        super.setListener()
        mTvJump.setOnClickListener(this)
    }

    override fun setView() {
        super.setView()
        loadData()
        setJumpLayout()
        hideTitleBar()
        initViewPager()
        initIndicatorView()
    }

    override fun needShowLoading(): Boolean {
        return false
    }

    override fun loadData() {
        super.loadData()
        val imageInfos = GlobalInfoManager.getInstance().getBannerInfo(BannerPosition.INTRODUCTION)
        if (imageInfos.isNullOrEmpty()) {
            mCommonPresenter.getBannerList(BannerPosition.INTRODUCTION)
        } else {
            updateData(imageInfos)
        }
        mCommonPresenter.getBannerList(BannerPosition.LOGIN_REGISTER)
    }

    private fun setJumpLayout() {
        val statusBarHeight = StatusBarUtil.getStatusBarHeight(mContext)
        val layoutParams = mTvJump.layoutParams as FrameLayout.LayoutParams
        layoutParams.topMargin += statusBarHeight
    }

    private fun initViewPager() {
        mViewPager.adapter = mAdapter
        mViewPager.offscreenPageLimit = 3
        mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mIndicatorViews.forEachIndexed { index, imageView ->
                    if (position == index) {
                        imageView.setImageResource(R.drawable.ic_introduction_indicator_select)
                    } else {
                        imageView.setImageResource(R.drawable.ic_introduction_indicator_unselect)
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    private fun initIndicatorView() {
        mIndicatorViews.clear()
        mLlIndicator.removeAllViews()
        mIntroductionList.forEachIndexed { index, _ ->
            val view = ImageView(mContext)
            mIndicatorViews.add(view)
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT
            )
            val dp6 = mContext.resources.getDimension(com.unionftech.common.R.dimen.dp_6).toInt()
            layoutParams.setMargins(dp6, 0, dp6, 0)
            view.layoutParams = layoutParams
            if (index == 0) {
                view.setImageResource(R.drawable.ic_introduction_indicator_select)
            } else {
                view.setImageResource(R.drawable.ic_introduction_indicator_unselect)
            }
            mLlIndicator.addView(view)
        }
    }

    override fun statusBar() {
        fullScreen()
    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mLastX = ev.x
            }

            //监听用户手指滑动，如果再最后一页，而且还在左滑,则跳转下个页面
            MotionEvent.ACTION_MOVE -> {
                if (mViewPager.currentItem == mIndicatorViews.size - 1) {
                    val distance = ev.x - mLastX
                    val touchSlop = swipeThreshold
                    if (abs(distance) > touchSlop) {
                        val rtl = Utils.isRTL()
                        if (!rtl) {
                            if (distance < 0) {
                                gotoNextActivity()
                                return true
                            }
                        } else {
                            if (distance > 0) {
                                gotoNextActivity()
                                return true
                            }
                        }
                    }
                }
            }

            MotionEvent.ACTION_UP -> {
                mLastX = 0f
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_jump -> {
                gotoNextActivity()
            }
        }
    }

    private fun gotoNextActivity() {
        SpUtils.getInstance().remove(CommonConstants.Key.KEY_IS_DARK_MODE)
        SpUtils.getInstance().remove(CommonConstants.Key.KEY_FOLLOW_SYSTEM)
        if (mLoginService?.checkLogin() == true) {
            UFMainStandardActivity.startThis(mContext)
            finish()
        } else {
            UFLoginRegisterActivity.startThis(mContext)
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
        }
    }


    override fun handleBannerView(
        position: BannerPosition, response: ResponseResult<List<BannerImageInfo>>
    ) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also { list ->
                if (position == BannerPosition.INTRODUCTION) {
                    updateData(list)
                } else {
                    preloadImage(position, list)
                }
            }
        } else {
            LogUtils.d(TAG, "handleBannerView error->$response")
        }
    }

    private fun preloadImage(
        position: BannerPosition, list: List<BannerImageInfo>
    ) {
        GlobalInfoManager.getInstance().putBannerInfo(position, list)
        for (info in list) {
            GlideImagerLoader.preloadImage(mContext, info.imageUrl)
        }
    }

    private fun updateData(list: List<BannerImageInfo>) {
        if (list.isEmpty()) {
            return
        }
        mIntroductionList.clear()
        list.forEachIndexed { index, bannerImageInfo ->
            when (index) {
                0 -> mIntroductionList.add(
                    IntroductionInfo(
                        R.drawable.icon_introduction_1, bannerImageInfo.imageUrl
                    )
                )

                1 -> mIntroductionList.add(
                    IntroductionInfo(
                        R.drawable.icon_introduction_2, bannerImageInfo.imageUrl
                    )
                )

                else -> mIntroductionList.add(
                    IntroductionInfo(
                        R.drawable.icon_introduction_3, bannerImageInfo.imageUrl
                    )
                )
            }
        }
        initIndicatorView()
        mAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}